<?php


namespace App\Services\Goods;

use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Goods\Attributes;
use App\Models\Goods\Specs;
use App\Services\BaseService;

/**
 * 商品属性相关业务类
 *
 * @package App\Http\Services
 * @author WangBin
 * @date 2021-06/11
 */
class AttributeService extends BaseService
{
    /**
     * 保存规格
     *
     * @param array $data
     * @return mixed
     * @throws BusinessException
     */
    public function update(array $data)
    {
        if(!empty($data['attribute_id'])) {
            $spec = Specs::getById($data['attribute_id']);
            if(is_null($spec)) {
                throw new BusinessException(ResponseCode::GOODS_ATTR_NOT_FOUND);
            }
        }
        // 校验名称唯一
        $ret = Attributes::checkUnique('name', $data['name'], $data['attribute_id']);
        if($ret) {
            throw new BusinessException(ResponseCode::GOODS_ATTR_NAME_EXIST);
        }
        // 校验编号唯一
        $ret = Attributes::checkUnique('attr_bn', $data['attr_bn'], $data['attribute_id']);
        if($ret) {
            throw new BusinessException(ResponseCode::GOODS_ATTR_BN_EXIST);
        }
        return Attributes::saveData($data);
    }

    /**
     * 规格列表
     *
     * @param array $filter
     * @return array
     */
    public function getList(array $filter)
    {
        $result = ['total' => 0, 'list' => []];
        $specs = Attributes::getByFilter($filter);
        if(empty($filter['no_page'])) {
            $specs->offset($filter['page'] * $filter['limit'])->limit($filter['limit']);
        }
        $result['total'] = $specs->count();
        $result['list'] = $specs->get();
        return $result;
    }

    /**
     * 获取属性详情
     *
     * @param int $attrId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws BusinessException
     */
    public function get(int $attrId)
    {
        $attribute = Attributes::getById($attrId);
        if(is_null($attribute)) {
            throw new BusinessException(ResponseCode::GOODS_ATTR_NOT_FOUND);
        }
        return $attribute;
    }

    /**
     * 删除属性
     *
     * @param string $attrId
     * @return mixed
     */
    public function delete(string $attrId)
    {
        $attrIds = explode(',', $attrId);
        return Attributes::remove($attrIds);
    }

    /**
     * 停/启用属性
     *
     * @param int $attrId
     * @return mixed
     * @throws
     */
    public function enable(int $attrId)
    {
        $attribute = Attributes::getById($attrId);
        if(is_null($attribute)) {
            throw new BusinessException(ResponseCode::GOODS_ATTR_NOT_FOUND);
        }
        $isActive = $attribute->is_active == 1 ? 0 : 1;
        return Attributes::enable($attrId, $isActive);
    }
}